package com.zxy.express.service.impl;

import com.autopai.base.common.mybatis.service.impl.BaseServiceImpl;
import com.autopai.base.common.tools.utils.DateUtils;
import com.autopai.base.common.web.constant.Constant;
import com.autopai.base.common.web.convert.ConvertUtils;
import com.autopai.base.common.web.model.RestResult;
import com.autopai.base.common.web.page.PageData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.zxy.express.dao.PracticeRecordDao;
import com.zxy.express.dto.PracticeRecordDTO;
import com.zxy.express.entity.PracticeRecordEntity;
import com.zxy.express.service.PracticeRecordService;
import io.swagger.models.auth.In;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 总练习记录表
 *
 * @author zhangxiying ${email}
 * @since ${version} 2025-07-01
 */
@Service
public class PracticeRecordServiceImpl extends BaseServiceImpl<PracticeRecordDao, PracticeRecordEntity> implements PracticeRecordService {

    @Autowired
    private UserManager userManager;
    @Override
    public PageData<PracticeRecordDTO> page(Map<String, Object> params) {
        IPage<PracticeRecordEntity> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );

        return getPageData(page, PracticeRecordDTO.class);
    }

    @Override
    public List<PracticeRecordDTO> list(Map<String, Object> params) {
        List<PracticeRecordEntity> entityList = baseDao.selectList(getWrapper(params));

        return ConvertUtils.sourceToTarget(entityList, PracticeRecordDTO.class);
    }

    private QueryWrapper<PracticeRecordEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<PracticeRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public PracticeRecordDTO get(String id) {
        PracticeRecordEntity entity = baseDao.selectById(id);

        return ConvertUtils.sourceToTarget(entity, PracticeRecordDTO.class);
    }

    @Override
    public void save(PracticeRecordDTO dto) {
        PracticeRecordEntity entity = ConvertUtils.sourceToTarget(dto, PracticeRecordEntity.class);
        Long userId=userManager.getUserId();
        entity.setUserId(userId);
        insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PracticeRecordDTO dto) {
        PracticeRecordEntity entity = ConvertUtils.sourceToTarget(dto, PracticeRecordEntity.class);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] ids) {
        //逻辑删除
        //logicDelete(ids, PracticeRecordEntity.class);

        //物理删除
        baseDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public RestResult getPracticeStatis() {
        //获取学习天数
        Long usrId = userManager.getUserId();
        Integer practiceDayCount =baseDao.getPracticeDayCount(usrId);
        practiceDayCount = practiceDayCount == null ? 0 : practiceDayCount;
        //获取学习素材数量
        Integer practiceMaterialCount =baseDao.getPracticeMaterialCount(usrId);
        practiceMaterialCount = practiceMaterialCount == null ? 0 : practiceMaterialCount;
        Integer practiceTotalTime =baseDao.getPracticeTotalTime(usrId);
        practiceTotalTime = practiceTotalTime == null ? 0 : practiceTotalTime;
        Map<String,Object> result = new HashMap<>();
        result.put("practiceDayCount",practiceDayCount);
        result.put("practiceMaterialCount",practiceMaterialCount);
        result.put("practiceTotalTime",practiceTotalTime);
        return new RestResult().ok(result);
    }

    @Override
    public RestResult getPracticeCalendar(Map<String, Object> params) {
        String dateStr=(String)params.get("date");
        String pattern = "yyyy-MM-dd";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        LocalDate date = LocalDate.parse(dateStr, formatter);
        // 获取当月的起始日期
        String firstDayOfMonth = date.withDayOfMonth(1).toString();
        firstDayOfMonth = firstDayOfMonth+" 00:00:00";
        // 获取当月的结束日期
        String lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth()).toString();
        lastDayOfMonth = lastDayOfMonth+" 23:59:59";
        List<PracticeRecordDTO> list=baseDao.getPracticeDate(userManager.getUserId(), firstDayOfMonth,lastDayOfMonth);
        List<String> dataList= Lists.newArrayList();
        for(PracticeRecordDTO dto:list){
            dataList.add(DateUtils.format(dto.getCreateDate(),pattern));
        }
        return new RestResult().ok(dataList);
    }

}